<?php

namespace app\model;


use MoCommon\WeChat\Wx;
use think\facade\Config;
use think\facade\Cache;
use think\facade\Env;
use think\facade\Log;

class Util
{
    /**
     * @desc  获取access_token 并保存
     * @author charlesyq
     * @return mixed
     */
    public static function get_access_token()
    {
        $wechat = Config::get('app.wechat');
        $website = Config::get('app.website');
        $appid = $wechat['appid'];
        $secret = $wechat['secret'];

        $options = Config::get('app.converse');
        $redis = Cache::init($options);

        Wx::init([$appid, $secret]);

        // 获取基础 access_token
        $access_token = $redis->get($website['index'] . '_access_token');

        if (empty($access_token)) {
            $access = Wx::access_token();
            $access_token = $access['access_token'];
            $redis->set($website['index'] . '_access_token', $access_token, $access['expires_in'] - 600);
        }
        return $access_token;
    }

    /**
     * @desc  更新 access_token 并保存
     * @author charlesyq
     * @return mixed
     */
    public static function update_access_token()
    {

        $options = Config::get('app.converse');
        $redis = Cache::init($options);
        $website = Config::get('app.website');
        $access = Wx::access_token();
        $access_token = $access['access_token'];
        $redis->set($website['index'] . '_access_token', $access_token, $access['expires_in'] - 300);
        return $access_token;
    }


    /**
     * 小程序发送模板消息
     * @param $send_members 发送的用户集合信息
     * @param $send_data 发送的data信息
     * @param $page 点击跳转地址
     */
    public static function send_prize_template($send_members,$send_data,$page)
    {
        if ($send_members) {
            $wechat = Config::get('app.wechat');
            $access_token = Util::get_access_token();
            Log::init([
                'type' => 'File',
                'path' => Env::get("root_path") . 'public/logs/'
            ]);
            $tpl_id = $wechat['msgtempid'];
            foreach ($send_members as $item) {
                $tpl_ret = Wx::sp_send_template($access_token, $item['openid'], $tpl_id, $send_data, $page, $item['formid']);
                Log::init([
                    'type' => 'File',
                    'path' => Env::get("root_path") . 'public/logs/'
                ]);
                Log::error("\r\n".date('Y-m-d H:i:s')."  ".json_encode($tpl_ret));

            }
        }
    }

    /**
     * 小程序生成带参数的二维码
     */
    public static function sp_qrcode_create($data)
    {
        $access_token = Util::get_access_token();
        $imgdata = Wx::sp_qrcode_create($access_token, $data);
        //生成二维码
        $base64_image = "data:image/jpeg;base64," . base64_encode($imgdata);
        return $base64_image;
    }


}

